import { baseURL } from './env'
export default async(url = '', data = {}, type = 'GET', method = 'fetch', contentType = 'application/json') => {
	type = type.toUpperCase();
	url = baseURL + url;

	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {
		let requestConfig = {
			credentials: 'include',
			method: type,
			headers: {
				'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Content-Type': contentType,
        'token': sessionStorage._router_userInfo_ ? JSON.parse(sessionStorage._router_userInfo_).user.token : ''
			},
			mode: "cors",
			cache: "force-cache"
		}

		if (type == 'POST') {
			let CASTGC= '_this.getURLParam().CASTGC'
			if(contentType === 'application/json' ) {
//				url = url + '?CASTGC=' + CASTGC;
			} else {
				data = Object.assign({}, data)
			}

			Object.defineProperty(requestConfig, 'body', {
				value: JSON.stringify(data)
			})
		}

		try {
			const response = await fetch(url, requestConfig)
      const responseJson = await response.json()
      if(responseJson.errorCode === '123104'){
        // var confirm = window.confirm('您的身份已过期，请重新登录~')
        // if (confirm) {
        location.href='#/login'
        return
        // }
      }
			if(responseJson && responseJson.errorCode && responseJson.errorCode == "ibox-uc-0001") {
				location.href='#/login'
			} else {
				return responseJson
			}

		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				data = Object.assign({}, data, {CASTGC: '_this.getURLParam().CASTGC'})
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object') {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}
